import { request } from "./index";
import type { User, UserProfile, PageResponse } from "@/types/user";

// 用户API接口
export const userApi = {
  /**
   * 获取用户资料
   */
  getProfile(userId: string): Promise<UserProfile> {
    return request.get(`/users/${userId}/profile`);
  },

  /**
   * 更新用户资料
   */
  updateProfile(
    userId: string,
    data: Partial<UserProfile>,
  ): Promise<UserProfile> {
    return request.put(`/users/${userId}/profile`, data, {
      showLoading: true,
      loadingText: "更新中...",
    });
  },

  /**
   * 上传头像
   */
  uploadAvatar(userId: string, file: File): Promise<{ avatarUrl: string }> {
    const formData = new FormData();
    formData.append("avatar", file);

    return request.upload(`/users/${userId}/avatar`, formData, {
      showLoading: true,
      loadingText: "上传中...",
    });
  },

  /**
   * 更新用户偏好设置
   */
  updatePreferences(
    userId: string,
    preferences: Record<string, any>,
  ): Promise<void> {
    return request.put(`/users/${userId}/preferences`, preferences);
  },

  /**
   * 获取用户偏好设置
   */
  getPreferences(userId: string): Promise<Record<string, any>> {
    return request.get(`/users/${userId}/preferences`);
  },

  /**
   * 修改密码
   */
  changePassword(
    userId: string,
    oldPassword: string,
    newPassword: string,
  ): Promise<void> {
    return request.put(
      `/users/${userId}/password`,
      {
        oldPassword,
        newPassword,
      },
      {
        showLoading: true,
        loadingText: "修改中...",
      },
    );
  },

  /**
   * 更新邮箱
   */
  updateEmail(
    userId: string,
    newEmail: string,
    verificationCode: string,
  ): Promise<void> {
    return request.put(
      `/users/${userId}/email`,
      {
        newEmail,
        verificationCode,
      },
      {
        showLoading: true,
        loadingText: "更新中...",
      },
    );
  },

  /**
   * 更新手机号
   */
  updatePhone(
    userId: string,
    newPhone: string,
    verificationCode: string,
  ): Promise<void> {
    return request.put(
      `/users/${userId}/phone`,
      {
        newPhone,
        verificationCode,
      },
      {
        showLoading: true,
        loadingText: "更新中...",
      },
    );
  },

  /**
   * 获取用户统计信息
   */
  getStats(userId: string): Promise<{
    totalSessions: number;
    totalMessages: number;
    totalTokensUsed: number;
    favoritePersonas: string[];
    joinDate: string;
    lastActiveDate: string;
    usageToday: number;
    usageThisMonth: number;
  }> {
    return request.get(`/users/${userId}/stats`);
  },

  /**
   * 获取用户使用历史
   */
  getUsageHistory(
    userId: string,
    period: "day" | "week" | "month" = "week",
  ): Promise<
    Array<{
      date: string;
      sessions: number;
      messages: number;
      tokensUsed: number;
    }>
  > {
    return request.get(`/users/${userId}/usage-history`, { period });
  },

  /**
   * 获取用户收藏的对话
   */
  getFavoriteChats(
    userId: string,
    page = 0,
    size = 20,
  ): Promise<
    PageResponse<{
      id: string;
      title: string;
      personaName: string;
      lastMessage: string;
      createdAt: string;
      messageCount: number;
    }>
  > {
    return request.get(`/users/${userId}/favorite-chats`, { page, size });
  },

  /**
   * 收藏对话
   */
  favoriteChat(userId: string, sessionId: string): Promise<void> {
    return request.post(`/users/${userId}/favorite-chats`, { sessionId });
  },

  /**
   * 取消收藏对话
   */
  unfavoriteChat(userId: string, sessionId: string): Promise<void> {
    return request.delete(`/users/${userId}/favorite-chats`, { sessionId });
  },

  /**
   * 获取用户标签
   */
  getTags(userId: string): Promise<
    Array<{
      id: string;
      name: string;
      color: string;
      count: number;
    }>
  > {
    return request.get(`/users/${userId}/tags`);
  },

  /**
   * 创建标签
   */
  createTag(
    userId: string,
    name: string,
    color: string,
  ): Promise<{
    id: string;
    name: string;
    color: string;
  }> {
    return request.post(`/users/${userId}/tags`, { name, color });
  },

  /**
   * 更新标签
   */
  updateTag(
    userId: string,
    tagId: string,
    name: string,
    color: string,
  ): Promise<void> {
    return request.put(`/users/${userId}/tags/${tagId}`, { name, color });
  },

  /**
   * 删除标签
   */
  deleteTag(userId: string, tagId: string): Promise<void> {
    return request.delete(`/users/${userId}/tags/${tagId}`);
  },

  /**
   * 获取用户通知设置
   */
  getNotificationSettings(userId: string): Promise<{
    emailNotifications: boolean;
    pushNotifications: boolean;
    smsNotifications: boolean;
    marketingEmails: boolean;
    securityAlerts: boolean;
    chatNotifications: boolean;
    personaUpdates: boolean;
  }> {
    return request.get(`/users/${userId}/notification-settings`);
  },

  /**
   * 更新通知设置
   */
  updateNotificationSettings(
    userId: string,
    settings: Record<string, boolean>,
  ): Promise<void> {
    return request.put(`/users/${userId}/notification-settings`, settings);
  },

  /**
   * 获取用户隐私设置
   */
  getPrivacySettings(userId: string): Promise<{
    profileVisibility: "public" | "friends" | "private";
    showOnlineStatus: boolean;
    allowDirectMessages: boolean;
    shareUsageStats: boolean;
    dataCollection: boolean;
  }> {
    return request.get(`/users/${userId}/privacy-settings`);
  },

  /**
   * 更新隐私设置
   */
  updatePrivacySettings(
    userId: string,
    settings: Record<string, any>,
  ): Promise<void> {
    return request.put(`/users/${userId}/privacy-settings`, settings);
  },

  /**
   * 导出用户数据
   */
  exportData(userId: string, format: "json" | "csv" = "json"): Promise<void> {
    return request.download(
      `/users/${userId}/export`,
      { format },
      `user_data_${userId}.${format}`,
    );
  },

  /**
   * 删除用户账户
   */
  deleteAccount(
    userId: string,
    password: string,
    reason?: string,
  ): Promise<void> {
    return request.delete(
      `/users/${userId}`,
      {
        password,
        reason,
      },
      {
        showLoading: true,
        loadingText: "删除中...",
      },
    );
  },

  /**
   * 获取用户订阅信息
   */
  getSubscription(userId: string): Promise<{
    plan: "free" | "premium" | "pro";
    status: "active" | "cancelled" | "expired";
    startDate: string;
    endDate?: string;
    features: string[];
    usage: {
      messagesUsed: number;
      messagesLimit: number;
      tokensUsed: number;
      tokensLimit: number;
    };
  }> {
    return request.get(`/users/${userId}/subscription`);
  },

  /**
   * 升级订阅
   */
  upgradeSubscription(
    userId: string,
    plan: "premium" | "pro",
    paymentMethod: string,
  ): Promise<{
    paymentUrl: string;
    orderId: string;
  }> {
    return request.post(
      `/users/${userId}/subscription/upgrade`,
      {
        plan,
        paymentMethod,
      },
      {
        showLoading: true,
        loadingText: "处理中...",
      },
    );
  },

  /**
   * 取消订阅
   */
  cancelSubscription(userId: string, reason?: string): Promise<void> {
    return request.post(
      `/users/${userId}/subscription/cancel`,
      {
        reason,
      },
      {
        showLoading: true,
        loadingText: "取消中...",
      },
    );
  },

  /**
   * 获取用户邀请码
   */
  getInviteCode(userId: string): Promise<{
    code: string;
    usageCount: number;
    maxUsage: number;
    expiresAt?: string;
  }> {
    return request.get(`/users/${userId}/invite-code`);
  },

  /**
   * 生成新的邀请码
   */
  generateInviteCode(userId: string): Promise<{
    code: string;
    expiresAt?: string;
  }> {
    return request.post(`/users/${userId}/invite-code`);
  },

  /**
   * 获取邀请历史
   */
  getInviteHistory(userId: string): Promise<
    Array<{
      inviteeUsername: string;
      inviteDate: string;
      status: "pending" | "accepted" | "expired";
      reward?: string;
    }>
  > {
    return request.get(`/users/${userId}/invite-history`);
  },
};
